<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/1/17
 * Time: 3:47 下午
 * description: Goods.php
 */

namespace app\home\business;


use app\common\model\Spec;
use app\common\model\SpecValue;

class Goods
{
    /**
     * 商品列表
     * @param $cate_id
     * @return \app\common\model\Goods|\think\Paginator
     */
    public static function list($cate_id){
        return \app\common\model\Goods::where('cate_id',$cate_id)->field('id,goods_name,goods_logo,goods_price')->paginate([
            'list_rows' => 10,
            'query' => [
                'cate_id' => $cate_id
            ],
        ]);
    }

    /**
     * 商品详情
     */
    public static function detail($id){
        # 查询详情
        $info = \app\common\model\Goods::with(['images','type','sku'])->find($id)->toArray();
        # 处理属性
        $info['goods_attr'] = json_decode($info['goods_attr'],true);
        # 查询规格值
        $spec_value_ids = array_unique(explode('_',implode('_',array_column($info['sku'],'value_ids'))));
        $spec_values = SpecValue::whereIn('id',$spec_value_ids)->select()->toArray();
        # 查询规格名
        $spec_ids = array_unique(array_column($spec_values,'spec_id'));
        $spec = Spec::whereIn('id',$spec_ids)->select()->toArray();
        foreach ($spec as $key => $value) {
            foreach ($spec_values as $item) {
                if ($item['spec_id'] == $value['id']) {
                    $spec[$key]['values'][] = [
                        'id' =>$item['id'],
                        'value' =>$item['spec_value'],
                    ];
                }
            }
        }
        # 处理sku规格组合、前端动态展示价格
        $info['spec'] = $spec;
//        [ 黑色32 '1_6' => ['price' => 600,'id' => 1],
//          黑色64G '1_7' => ['price' => 600,'id' => 2],
//        ];
        $skuNew = [];
        foreach ($info['sku'] as $item) {
            $skuNew[$item['value_ids']] = [
                'price' => $item['price'],# sku价格
                'id' => $item['id'],# skuid
            ];
        }
        $info['sku'] = json_encode($skuNew,true);
        return $info;
    }

}